package experiment5.demo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server implements ScreenSayIntf {
    List<SocketHandler> clients = new ArrayList<SocketHandler>();
    ScreenInput screenInput;
    ServerSocket serverSocket;

    public Server() {

    }

    public void start() {
        screenInput = new ScreenInput(this);
        screenInput.start();
        try {
            serverSocket = new ServerSocket(888);
            Socket socket;
            while ((socket = serverSocket.accept()) != null) {
                SocketHandler socketHandler = new SocketHandler(socket);
                socketHandler.start();
                clients.add(socketHandler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    @Override
    public void say(String content) {
        for (int i = 0; i < clients.size(); i++) {
            clients.get(i).sayTo(content);
        }
    }
}
